package com.plentitude.easytrader.ui;

import com.plentitude.easytrader.R;
import com.plentitude.easytrader.util.CustomProgressDialog;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.widget.CheckBox;
import android.widget.EditText;


/**
 * Front-door {@link Activity}.
 * 
 * @author team@getstarted.com.ua
 */
public class HomeActivity extends Activity {
	private SharedPreferences settings;
	private CustomProgressDialog progressDialog;
	
	
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);

        settings = getSharedPreferences(Keys.KEY, 0);
        boolean firstRun = settings.getBoolean(Keys.FIRST_RUN, true);
        if(firstRun) {
        	final Intent intent = new Intent(HomeActivity.this, LicenseActivity.class);
	        startActivity(intent);
	        finish();
        } else {
	        doWelcome();
	        doNotification();
        }
    }
    
    /** Handle "login" action. */
    public void onLogin(View v) {
    	EditText username = (EditText) findViewById(R.id.username); 
    	EditText password = (EditText) findViewById(R.id.password);
    	CheckBox rememberMe = (CheckBox) findViewById(R.id.rememberMe);
    	
    	if(!validate(username) || !validate(password)) {
    		return;
    	} else {
    		ETApplication.getInstance().setUsername(username.getText().toString());
    		ETApplication.getInstance().setUsername(password.getText().toString());
    		SharedPreferences.Editor editor = settings.edit();
    		if(rememberMe.isChecked()) {
    		    editor.putString(Keys.USERNAME, username.getText().toString());
    		    editor.putString(Keys.PASSWORD, password.getText().toString());
    		} else {
    		    editor.remove(Keys.USERNAME);
    		    editor.remove(Keys.PASSWORD);
    		}
		    editor.putBoolean(Keys.REMEMBER_ME, rememberMe.isChecked());
		    editor.commit();
    	}
    	
    	if(!ETApplication.getInstance().isOnline(true)) {
    		// Connection failure
    		Builder alert = new AlertDialog.Builder(this)
            .setTitle(R.string.attention)
            .setIcon(android.R.drawable.ic_dialog_alert)
            .setMessage(R.string.login_failed)
            .setNegativeButton(R.string.no, null)
            .setPositiveButton(R.string.yes, new OnClickListener() {
				@Override
				public void onClick(DialogInterface arg0, int arg1) {
					onLogin(null);
				}
            })
            .setCancelable(false);
        	alert.show(); 
    	} else {
    		// Login
    		new LoginTask().execute();
    	}
    }
   
    /** Handle "create new" action. */
    public void onCreateNew(View v) {
    	final Intent intent = new Intent(HomeActivity.this, AccountActivity.class);
        startActivity(intent);
    }
    
    class LoginTask extends AsyncTask<String, String, Boolean>{
    	@Override
    	protected void onPreExecute() {
    		progressDialog = CustomProgressDialog.show(HomeActivity.this, null, null);
    	}
    	
    	@Override
    	protected Boolean doInBackground(String... params) {
    		Boolean ret = doLogin(); 
    		return ret;
    	}

    	@Override
    	protected void onPostExecute(Boolean result) {
    		if(progressDialog != null) progressDialog.dismiss();
    		if(result) {
    			final Intent intent = new Intent(HomeActivity.this, WatchlistActivity.class);
    	        startActivity(intent);
    	        finish();
    		} else {
	    		// Authentication failure
	    		Builder alert = new AlertDialog.Builder(HomeActivity.this)
	            .setTitle(R.string.attention)
	            .setIcon(android.R.drawable.ic_dialog_alert)
	            .setMessage(R.string.auth_failure)
	            .setNegativeButton(R.string.no, null)
	            .setPositiveButton(R.string.yes, new OnClickListener() {
					@Override
					public void onClick(DialogInterface arg0, int arg1) {
						// Generate a new product key
						SharedPreferences.Editor editor = settings.edit();
			    		editor.remove(Keys.PRODUCT_KEY);
						editor.commit();
			    		onLogin(null);
					}
	            })
	            .setCancelable(false);
	        	alert.show();
    		}
    	}
    }

    @Override
    protected void onDestroy() {
    	super.onDestroy();
    	settings = null;
    	progressDialog = null;
    }
    
    @Override
	public boolean onCreateOptionsMenu(Menu menu) {
	    MenuInflater inflater = getMenuInflater();
	    inflater.inflate(R.menu.menu_main, menu);
        return true;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		Intent intent = null;
		switch (item.getItemId()) {
		    case R.id.help:
		    	intent = new Intent(HomeActivity.this, HelpActivity.class);
		        startActivity(intent);
		    	return true;
		    case R.id.settings:
		    	intent = new Intent(HomeActivity.this, SettingsActivity.class);
		        startActivity(intent);
		    	return true;
		    case R.id.info:
		    	intent = new Intent(HomeActivity.this, InfoActivity.class);
		        startActivity(intent);
		    	return true;
		    case R.id.notifications:
		    	intent = new Intent(HomeActivity.this, NotifyActivity.class);
		        startActivity(intent);
		    	return true;
		    case R.id.website:
		    	onWebLinkClick();
		    	return true;
		    case R.id.update:
		    	return true;
		    default:
		    	return true;
	    }
	}
    
	
    // PRIVATE METHODS
    
    /** Display welcome page */
    private void doWelcome() {
        setContentView(R.layout.activity_welcome);
    	// Retrieve stored credentials if rememberMe was checked before
    	EditText username = (EditText) findViewById(R.id.username); 
    	EditText password = (EditText) findViewById(R.id.password);
    	CheckBox rememberMe = (CheckBox) findViewById(R.id.rememberMe);
    	username.setText(settings.getString(Keys.USERNAME, Keys.E));
    	password.setText(settings.getString(Keys.PASSWORD, Keys.E));
    	rememberMe.setChecked(settings.getBoolean(Keys.REMEMBER_ME, false));
        getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.title);
    }
    
    /** Login with credentials provided */
    private boolean doLogin() {
    	boolean ret = false;
    	String username = settings.getString(Keys.USERNAME, Keys.E);
    	String oldProductKey = settings.getString(Keys.PRODUCT_KEY, Keys.E);

    	if(TextUtils.isEmpty(oldProductKey)) {
        	String productKey = ETApplication.getInstance().getSecurityManager().changeProductKey(username);
        	if(productKey != null) {
    	    	SharedPreferences.Editor editor = settings.edit();
    			editor.putString(Keys.PRODUCT_KEY, productKey);
    			editor.commit();
    			ret = true;
        	}
    	} else {
    		String productKey = ETApplication.getInstance().getSecurityManager().getProductKey(username);
    		ret = oldProductKey.equals(productKey);
    	}
    	return ret;
    }
    
    /** Validate credentials provided */
    private boolean validate(EditText credential) {
    	boolean ret = !(credential==null || credential.getText()==null || 
    		TextUtils.isEmpty(credential.getText().toString().trim()) || credential.getText().toString().trim().length()<1);
    	return ret;
    }
    
    /** Create Notification in system tray */
    private void doNotification() {
        int icon = R.drawable.ic_launcher;		      				// icon from resources
        CharSequence tickerText = "Synchronize";            		// ticker-text
        long when = System.currentTimeMillis();        				// notification time
        Context context = getApplicationContext();      			// application Context
        CharSequence contentTitle = "EasyTraderApp notification";  	// expanded message title
        CharSequence contentText = "Updates are available";			// expanded message text

        Intent notificationIntent = new Intent(this, HomeActivity.class);
        PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);

        // the next two lines initialize the Notification, using the configurations above
        Notification notification = new Notification(icon, tickerText, when);
        notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);
        
        int HELLO_ID = 1;
        String ns = Context.NOTIFICATION_SERVICE;
        NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns);
        mNotificationManager.notify(HELLO_ID, notification);
    }
      

    
	/** Handle "web link" action. */
	private void onWebLinkClick() {
		startActivity(new Intent(Intent.ACTION_VIEW , Uri.parse(Keys.VISIT_URL)));
	}

}
